package com.xpalive.base.dto.page.impl;

import com.xpalive.base.dto.page.PageRsp;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.validation.constraints.NotNull;
import lombok.Data;
import org.springframework.util.Assert;

@Data
public class PageRspImpl<T> implements PageRsp<T>, Iterable<T>, Supplier<Stream<T>> {

    private long page;
    private long size;
    private long total;
    private long totalPage;
    private List<T> content;

    @Override
    public <U> PageRsp<U> map(Function<? super T, ? extends U> converter) {
        PageRspImpl<U> uxPage = new PageRspImpl<>();
        uxPage.setContent(getConvertedContent(converter));
        uxPage.setPage(page);
        uxPage.setSize(size);
        uxPage.setTotal(total);
        uxPage.setTotalPage(totalPage);
        return uxPage;
    }

    public Stream<T> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    protected <U> List<U> getConvertedContent(Function<? super T, ? extends U> converter) {

        Assert.notNull(converter, "Function must not be null!");

        return this.stream().map(converter).collect(Collectors.toList());
    }

    @Override
    @NotNull
    public Iterator<T> iterator() {
        return content.iterator();
    }

    @Override
    public Stream<T> get() {
        return stream();
    }
}
